# -*- coding: utf-8 -*-

# Copyright 2013 Ida Leter, adapted from Fanficdownloader
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#

import re
import os.path
import datetime
import string
import StringIO
import logging
import urllib2

from configurable import Configurable
from htmlcleanup import stripHTML

logger = logging.getLogger(__name__)

class BasePaperWriter(Configurable):

    @staticmethod
    def getFormatName():
        return 'base'

    @staticmethod
    def getFormatExt():
        return '.bse'

    def __init__(self, configuration, adapter):
        Configurable.__init__(self, configuration)

        self.adapter = adapter
        self.paper = adapter.getPaperMetadataOnly() # only cache the metadata initially.


    def getMetadata(self,key,):
        return stripHTML(self.paper.getMetadata(key))

    def getOutputFileName(self):
        return self.paper.formatFileName()

    def _write(self, out, text):
        out.write(text.encode('utf8'))

    # if no outstream is given, write to file.
    def writePaper(self,outstream=None, metaonly=False, outfilename=None, forceOverwrite=False):

        self.metaonly = metaonly
        if outfilename == None:
            outfilename=self.getOutputFileName()

        self.outfilename = outfilename

        if not outstream:
            close=True
            logger.info("Save directly to file: %s" % outfilename)

            if not metaonly:
                self.paper = self.adapter.getPaperMetadataOnly()
            outstream = open(outfilename,"wb")
        else:
            close=False
            logger.debug("Save to stream")

        if not metaonly:
            self.paper = self.adapter.getPaperMetadataOnly()

        self.writePaperImpl(outstream)

        if close:
            outstream.close()

    def writePaperImpl(self, out):
        # fix for acm, doesn't appear to work without it, everything else happily gets by
        if 'acm.org' in self.paper.getMetadata('pdfurl'):
            req = urllib2.Request(self.paper.getMetadata('pdfurl'), headers={'User-Agent' : "Mozilla/6.0 (Windows NT 6.2; WOW64; rv:16.0.1) Gecko/20121011 Firefox/16.0.1"})
        else:
            req = self.paper.getMetadata('pdfurl')
        pdfFile = urllib2.urlopen(req)
        out.write(pdfFile.read())